package cn.kimming.wms.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.kimming.wms.dao.IProductStockDAO;
import cn.kimming.wms.domain.Depot;
import cn.kimming.wms.domain.ProductStock;
import cn.kimming.wms.domain.StockIncomeBillItem;
import cn.kimming.wms.domain.StockOutcomeBillItem;
import cn.kimming.wms.excep.StockIsNotEnoughException;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.IProductStockService;

@Service("productStockService")
public class ProductStockServiceImpl implements IProductStockService {

	@Autowired
	private IProductStockDAO productStockDAO;
	
	@Override
	public void save(ProductStock obj) {
		productStockDAO.save(obj);
	}

	@Override
	public void update(ProductStock obj) {
		productStockDAO.update(obj);
	}

	@Override
	public void delete(Long id) {
		productStockDAO.delete(productStockDAO.get(id));
		
	}

	@Override
	public ProductStock get(Long id) {
		return productStockDAO.get(id);
	}

	@Override
	public List<ProductStock> list() {
		return productStockDAO.list();
	}

	@Override
	public List<ProductStock> query(QueryObject qo) {
		return productStockDAO.query(qo);
	}

	@Override
	public void stockIncome(Depot depot, StockIncomeBillItem item) {
		ProductStock ps = productStockDAO.getByDepotIdAndProductId(depot.getId(), item.getProduct().getId());
		if (ps == null) {
			//创建库存
			ps = new ProductStock();
			ps.setDepot(depot);
			ps.setProduct(item.getProduct());
			ps.setStockNumber(item.getNumber());
			ps.setPrice(item.getCostPrice());
			ps.setAmount(item.getAmount());
			productStockDAO.save(ps);
		} else {
			//修改库存(库存量,价格,总金额)
			ps.setStockNumber(ps.getStockNumber().add(item.getNumber()));
			ps.setAmount(ps.getAmount().add(item.getAmount()));
			ps.setPrice(ps.getAmount().divide(ps.getStockNumber(), 2, RoundingMode.HALF_UP));
			productStockDAO.update(ps);
			
		}
	}

	@Override
	public BigDecimal stockOutcome(Depot depot, StockOutcomeBillItem item) {
		ProductStock ps = productStockDAO.getByDepotIdAndProductId(depot.getId(), item.getProduct().getId());
		if (ps == null || ps.getStockNumber().compareTo(item.getNumber()) < 0) {
			throw new StockIsNotEnoughException(item);
		}
		ps.setStockNumber(ps.getStockNumber().subtract(item.getNumber()));
		ps.setAmount(ps.getPrice().multiply(ps.getStockNumber()).setScale(2, RoundingMode.HALF_UP));
		productStockDAO.update(ps);
		return ps.getPrice();
	}
}
